package service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"git.tmuyu.com.cn/beego/models"
	"git.tmuyu.com.cn/beego/util"
	"github.com/astaxie/beego/logs"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

const wxUserInforUrl = "https://api.weixin.qq.com/cgi-bin/user/info"

//测试使用
func FF(user *models.UserWx) (*models.UserWx, error) {
	o := util.GetMysqlDb()
	err := o.Model(&user).Create(&user).Error
	if err != nil {
		return nil, err
	}
	return user, nil
}

//获取用户信息
func FetchWxInfoAndIcon(wxUserInfo *models.WxUserInfo) (*models.WxUser, error) {
	o := util.GetMysqlDb()
	at := wxUserInfo
	wxUserInforUrl := wxUserInforUrl
	logs.Info("wxUserInforUrl", wxUserInforUrl)
	requestLine := strings.Join([]string{wxUserInforUrl,
		"?access_token=",
		at.AccessToken,
		"&openid=",
		at.Openid,
		"&lang=zh_CN"}, "")
	logs.Info("wxUserInforUrl", requestLine)
	resp, err := http.Get(requestLine)

	if err != nil || resp.StatusCode != http.StatusOK {
		fmt.Println("发送get请求获取 wxUserInfo 错误", err)
		logs.Error("发送get请求获取 wxUserInfo 错误", err)
		return nil, err
	}
	logs.Info("resp.StatusCode", resp.StatusCode)
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		fmt.Println("发送get请求获取 wxUserInfo 读取返回body错误", err)
		logs.Error("发送get请求获取 wxUserInfo 读取返回body错误", err)
		return nil, err
	}
	if bytes.Contains(body, []byte("errcode")) {
		ater := models.AccessTokenErrorResponse{}
		err = json.Unmarshal(body, &ater)
		logs.Info("出错:", ater)
		if err != nil {
			logs.Error("发送get请求获取 wxUserInfo 的错误信息 %+v\n", ater)
			return nil, err
		}
		return nil, fmt.Errorf("%s", ater.Errmsg)
	} else {
		atr := models.UserStruct{}
		err = json.Unmarshal(body, &atr)
		if err != nil {
			logs.Error("发送get请求获取 wxUserInfo 返回数据json解析错误", err)
			return nil, err
		}

		var user models.WxUser
		if atr.Unionid == "" {
			logs.Warn("用户openid：", atr.Openid)
			logs.Warn("用户无unionid：", atr.Unionid)
			return nil, fmt.Errorf("该用户无unionId")
		}
		if o.Where("union_id = ?", atr.Unionid).First(&user).RecordNotFound() {
			user.Openid = atr.Openid
			user.UnionId = atr.Unionid
			user.AcToken = at.AccessToken
			user.CreateAt = time.Now()
			user.ReToken = at.RefreshToken
			err := o.Create(&user).Error
			if err != nil {
				logs.Error("err:", err)
				return nil, err
			}
		} else {
			logs.Warn("该用户已经存在")
		}
		return &user, nil
	}

}
